package com.demo.nien;

import com.demo.util.Print;
import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lkz
 * @ClassName: CreateThreadPoolDemo
 * @description: 简单的线程工厂  ThreadFactory
 * @date 2022/6/14 13:49
 */
public class CreateThreadPoolDemo {

    static public class SimpleThreadFactory implements ThreadFactory {

        static AtomicInteger threadNo = new AtomicInteger(1);
        //实现其唯一的创建线程方法
        @Override
        public Thread newThread(Runnable target)
        {
            String threadName = "simpleThread-" + threadNo.get();
            Print.tco("创建一条线程，名称为：" + threadName);
            threadNo.incrementAndGet();
            //设置线程名称，和异步执行目标
            Thread thread = new Thread(target,threadName);
            //设置为守护线程
            thread.setDaemon(true);
            return thread;
        }
    }

    @Test
    public void testThreadFactory() throws InterruptedException {
        //使用自定义线程工厂，快捷创建一个固定大小线程池
        ExecutorService pool =
                Executors.newFixedThreadPool(2,new SimpleThreadFactory());
        for (int i = 0; i < 5; i++)
        {
            pool.submit(()->{
                System.out.println("kkkkkkk");
            });
        }
        //等待 10 秒
        Thread.sleep(1000);
        Print.tco("关闭线程池");
        pool.shutdown();
    }

}
